package com.fx.controller;

import com.alibaba.fastjson.JSON;
import com.fx.pojo.SysRole;
import com.fx.pojo.SysUser;
import com.fx.service.SysRoleService;
import com.fx.service.SysUserService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    @RequestMapping(value = "/login")
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String account, String password, HttpSession session){
//        int i = 1/0;
        SysUser user = sysUserService.login(account, password);

        if(user != null){
            session.setAttribute("userSession",user);
            return "redirect:/main";
        }
        return "login";
    }

    @RequestMapping(value = "/main")
    public String main(){

        return "frame";
    }

//    @ExceptionHandler(value = {RuntimeException.class})
//    public String handlerException(RuntimeException e, HttpServletRequest request){
//        request.setAttribute("e",e);
//        return "error";
//    }

    @RequestMapping(value = "/logout")
    public String logout( HttpSession session){
        session.removeAttribute("userSession");
        return "redirect:/login";
    }

    @RequestMapping(value = "/user/list")
    public String list(Model model,
                       String queryRealName,
                       Integer queryRoleId,
                       Integer pageIndex){

        //设置 第几页
        if (pageIndex == null){
            pageIndex = 1;
        }
        // 设置 页面大小
        Integer pageSize = 8;


        //查角色
        List<SysRole> roleList = sysRoleService.findList();

        List<SysUser> userList = sysUserService.findList(queryRealName,queryRoleId,pageIndex,pageSize);

        model.addAttribute("roleList",roleList);
        model.addAttribute("userList",userList);
        model.addAttribute("queryRealName",queryRealName);
        model.addAttribute("queryRoleId",queryRoleId);

        //总记录数
        Integer totalCount = sysUserService.count(queryRealName,queryRoleId);

        // totalPageCount 总页数 = 总记录数/页面大小  （不能整除+1）
        Integer totalPageCount = totalCount / pageSize;

        if (totalCount % pageSize != 0){
            totalPageCount ++ ;
        }

        model.addAttribute("currentPageNo",pageIndex);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("totalPageCount",totalPageCount);
        return "sysUser/list";
    }

    @RequestMapping(value = "user/add",method = RequestMethod.GET)
    public String toAdd(){

        return "sysUser/add";
    }

    @RequestMapping(value = "user/add",method = RequestMethod.POST)
    public String add(SysUser sysUser,
                      HttpSession session,
                      HttpServletRequest request,
                      @RequestParam(value = "idPic",required = false) MultipartFile idPic) {

        String fileName = "";

        if (!idPic.isEmpty()){

            //判断文件大小
            if (idPic.getSize() > 500000){
                request.setAttribute("uploadFileError","文件大小不能超过500kb");
                return "sysUser/add";
            }

            //判断文件类型
            // tgf.jpg
            if (!(idPic.getOriginalFilename().endsWith("jpg") || idPic.getOriginalFilename().endsWith("png"))){
                request.setAttribute("uploadFileError","文件格式不正确");
                return "sysUser/add";
            }

            try {
                //"D:\\289\\temp";
                String path = session.getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
                fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";//"gf.jpg";
                //目标文件
                File targetFile = new File(path,fileName);

                if (!targetFile.exists()){
                    targetFile.mkdirs();
                }

                //把文件流的数据输出到目标文件中
                idPic.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



        SysUser loginUser = (SysUser) session.getAttribute("userSession");

        sysUser.setIdPicPath(fileName);
        sysUser.setCreatedUserId(loginUser.getId());
        sysUser.setCreatedTime(new Date());

        if (sysUserService.add(sysUser)){
            return "redirect:/user/list";
        }

        return "sysUser/add";
    }


    @RequestMapping(value = "user/update",method = RequestMethod.GET)
    public String toUpdate(Integer uid,Model model){

        SysUser sysUser = sysUserService.findUserById(uid);
        model.addAttribute("sysUser",sysUser);

        return "sysUser/update";
    }

    @RequestMapping(value = "/user/view/{id}")
    public String view(@PathVariable Integer id, Model model){
        SysUser sysUser = sysUserService.findUserById(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/view";
    }
    ///user/ucexist
    @RequestMapping(value = "/user/ucexist")
    @ResponseBody
    public String ucexist(String account){

        // {"account":"exist"}

        SysUser sysUser = sysUserService.findUserByAccount(account);
        if (sysUser == null){
            return "{\"account\":\"notexist\"}";
        } else {
            return "{\"account\":\"exist\"}";
        }

    }

    @RequestMapping(value = "/user/viewjson/{id}")
    @ResponseBody
    public Object viewJson(@PathVariable Integer id){
        SysUser sysUser = sysUserService.findUserById(id);
        // {"id":1,"account":"admin",.....}
//        String jsonString = JSON.toJSONString(sysUser);
        return sysUser;
    }
}
